'''
Created on 2010-10-28

@author: frank
'''
import oauth.oauth as oauth
import gdata.service
import urllib
from lib.oauth.OAuthClient import OAuthClient

class DoubanSerive(gdata.service.GDataService):
    
    def __init__(self, 
                 consumer_token=None, 
                 consumer_token_secret=None, 
                 source="pybean", 
                 server='api.douban.com',
                 additional_headers=None):
        self.consumer_token = consumer_token
        self.consumer_token_secret = consumer_token_secret
        self.client = OAuthClient(self.consumer_token, self.consumer_token_secret)
        gdata.service.GDataService.__init__(self, service='douban', source=source, server=server, additional_headers=additional_headers)

    def getAuthorizationURL(self, key, secret, callback=None):    
        return self.client.get_authorize_url(key,secret, callback) 
    def programmaticLogin(self, access_token=None, access_token_secret=None, function=None):
        try:
            self.client.login(access_token, access_token_secret, function)
        except oauth.OAuthError as e:
            raise oauth.OAuthError(e.message)   
    def get(self, uri, extra_headers={}, *args, **kwargs):
        auth_header = self.client.get_oauth_header('GET', uri)
        if auth_header:
            extra_headers.update(auth_header)
        elif self.consumer_token:
            param = urllib.urlencode([('apikey', self.consumer_token)])
            if '?' in uri:
                uri += '&' + param
            else:
                uri += '?' + param
        return gdata.service.GDataService.Get(self, uri, extra_headers, *args, **kwargs)  
    def post(self, data, uri, extra_headers={}, url_params=None, *args, **kwargs):
        extra_headers.update(self.client.get_auth_header('POST', uri, url_params))
        return gdata.service.GDataService.Post(self, data, uri, 
                extra_headers, url_params, *args, **kwargs)
    
    def put(self, data, uri, extra_headers={}, url_params=None, *args, **kwargs):
        extra_headers.update(self.client.get_auth_header('PUT', uri, url_params))
        return gdata.service.GDataService.Put(self, data, uri, 
                extra_headers, url_params, *args, **kwargs)

    def delete(self, uri, extra_headers={}, url_params=None, *args, **kwargs):
        extra_headers.update(self.client.get_auth_header('DELETE', uri, url_params))
        return gdata.service.GDataService.Delete(self, 
                uri, extra_headers, url_params, *args, **kwargs)
                